import { useMemo } from 'react'
import { IProductInfoResponse } from '../inteface/product-info'

interface MaterialSelection {
  categoryId: number
  materialId: number
}

interface SelectedCustomization {
  [materialName: string]: MaterialSelection
}

interface UseMaterialSelectionParams {
  productInfoData: IProductInfoResponse | undefined
  selectedCustomization: SelectedCustomization
}

interface UseMaterialSelectionReturn {
  finalMaterialSelection: { [key: string]: MaterialSelection }
  materialIdsForApi: MaterialSelection[]
}

/**
 * 生成类别 ID（确保为数字类型）
 */
const getCategoryId = (id: number | string): number => {
  return typeof id === 'number' ? id : Number(id)
}

/**
 * useMaterialSelection Hook
 *
 * 生成最终的材料选择列表，用于 API 提交
 * 逻辑：
 * 1. 从默认套餐材料中提取所有材料
 * 2. 用用户自定义选择的材料覆盖默认值
 * 3. 转换为 API 需要的格式
 *
 * @param productInfoData - 产品信息
 * @param selectedCustomization - 用户自定义选择的材料
 * @returns 最终材料选择和 API 格式的材料 ID 列表
 */
export const useMaterialSelection = ({
  productInfoData,
  selectedCustomization,
}: UseMaterialSelectionParams): UseMaterialSelectionReturn => {
  // 生成最终的材料选择列表
  const finalMaterialSelection = useMemo(() => {
    const defaultMaterials: { [key: string]: MaterialSelection } = {}

    // 遍历默认套餐材料，生成初始材料选择对象
    productInfoData?.product.packageMaterials.categories.forEach((category) => {
      const categoryId = getCategoryId(category.id)

      category.subCategories.forEach((subCategory) => {
        subCategory.materials.forEach((material) => {
          // 使用 material.name 作为 key
          defaultMaterials[material.name] = {
            categoryId: material.categoryId || categoryId,
            materialId: material.id,
          }
        })
      })
    })

    // 用用户选择的材料覆盖默认值
    return {
      ...defaultMaterials,
      ...selectedCustomization,
    }
  }, [productInfoData?.product.packageMaterials.categories, selectedCustomization])

  // 转换为 API 需要的格式
  const materialIdsForApi = useMemo(() => {
    return Object.values(finalMaterialSelection).map((item) => ({
      categoryId: item.categoryId,
      materialId: item.materialId,
    }))
  }, [finalMaterialSelection])

  return {
    finalMaterialSelection,
    materialIdsForApi,
  }
}

